import shlex
import subprocess
import os


def start_app(cmd):
    os.popen(cmd)


def cmd_exec(cmd, timeout=10):
    result = list()
    print(cmd)
    try:
        cmd_list = shlex.split(cmd)
        proc = subprocess.Popen(cmd_list, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
    except Exception as e:
        print("Popen cmd_list failed:{},try to execute cmd with cmd=True")
        proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                                universal_newlines=True)

    try:
        res = proc.wait(timeout)
    except TimeoutError as e:
        proc.terminate()
        raise TimeoutError(str(e))
    else:
        out = proc.stdout.readlines()
        for line in out:
            print(line, end='')
            result.append(line.strip())
    return result, int(proc.returncode)
